package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.SpotTheme;
import cn.wolfcode.luowowo.article.domain.Ticket;
import cn.wolfcode.luowowo.article.domain.TicketDetail;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.ISpotThemeService;
import cn.wolfcode.luowowo.article.service.ITicketService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.order.domain.TicketOrder;
import cn.wolfcode.luowowo.order.service.ITicketOrderService;
import cn.wolfcode.luowowo.search.domain.TicketTemplate;
import cn.wolfcode.luowowo.search.query.TicketSeachQuery;
import cn.wolfcode.luowowo.search.service.ITicketSearchService;
import cn.wolfcode.luowowo.website.annoation.UserParam;
import cn.wolfcode.luowowo.website.web.util.alipay.AlipayConfig;
import cn.wolfcode.luowowo.website.web.util.alipay.GenerateOrderNoUtil;
import cn.wolfcode.luowowo.website.web.util.alipay.SaleProduct;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("ticket")
public class TicketController {
    @Reference
    private ITicketSearchService ticketSearchService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private ITicketService ticketService;

    @Reference
    private ITicketOrderService ticketOrderService;
    @Reference
    private ISpotThemeService spotThemeService;


    @RequestMapping("")
    public String ss1(Model model, @ModelAttribute("qo") TicketSeachQuery qo, @UserParam UserInfo userInfo) {

        //list.subList( 1,list.size() );
        Destination province = destinationService.getProvince( 3261L );
        List <Destination> children = province.getChildren();
        model.addAttribute( "list", children );
        List <Ticket> cts = ticketService.selectCommendTicketsTop4();
        model.addAttribute( "cts", cts );

        return "ticket/index";
    }

    //查询当前目的地下的所有景点
    @RequestMapping("reloadProd")
    public String reloadProd(Model model, Long ajaxDestId) {
        //根据目的地查询所有的主题
        List <SpotTheme> spotThemes = spotThemeService.selectbyDestId( ajaxDestId );
        model.addAttribute( "themes", spotThemes );
        //根据第一个主题的id 和目的地id 查询当前的ticket 集合
        List <Ticket> tickets = ticketService.selectBydestId( ajaxDestId );
        model.addAttribute( "tickets", tickets );
        return "ticket/ticketTemplate";
    }

    @RequestMapping("reloadThemeSpot")
    public String reloadProd(Model model, Long ajaxDestId, Long ajaxSubjectId) {
        List <SpotTheme> spotThemes = spotThemeService.selectbyDestId( ajaxDestId );
        model.addAttribute( "themes", spotThemes );
        //根据目的地和主题查询ticket
        List <Ticket> tickets = ticketService.selectBydestIdAndThemelId( ajaxDestId,ajaxSubjectId );
        model.addAttribute( "tickets", tickets );
        return "ticket/ticketTemplate";
    }

    @RequestMapping("/searchPage")
    public String searchPage(Model model, Long destId) {
        TicketSeachQuery qo = new TicketSeachQuery();
        qo.setDestId( destId );
        List <Ticket> tickets = ticketService.selectBydestId( destId );
        model.addAttribute( "tickets", tickets );
        return "ticket/ticketTemplate";
    }

    @RequestMapping("detail")
    public String detail(Long tid, Model model) {
        Ticket ticket = ticketService.selectbyId( tid );
        List <TicketDetail> ts = ticketService.selectBydestIdAndTicketlId( ticket.getDestination().getId(), tid );
        model.addAttribute( "ts", ts );
        model.addAttribute( "ticketDetail", ticket );

        return "ticket/detail";
    }

    @RequestMapping("addOrder")
    public String order(String tid, Model model) {

        TicketDetail ticketDetail = ticketService.selectTicketId( tid );
        model.addAttribute( "ticket", ticketDetail );
        return "ticket/addorder";
    }

    /**
     * 结算界面
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/payPage")
    public String payController(TicketOrder ticketOrder, String msgCode, @UserParam UserInfo userInfo) throws IOException {
        TicketDetail detail = ticketService.selectByPno( ticketOrder.getPno() );
        ticketOrder.setPnName( ticketOrder.getPnName() );
        ticketOrder.setOrderNO( GenerateOrderNoUtil.gen( "2019", 10L ) );
        ticketOrderService.save( ticketOrder, msgCode, userInfo );
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient( AlipayConfig.gatewayUrl, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type );
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl( AlipayConfig.return_url );
        alipayRequest.setNotifyUrl( AlipayConfig.notify_url );
        SaleProduct saleProduct = new SaleProduct();

        saleProduct.setOut_trade_no( GenerateOrderNoUtil.gen( "2019", 10L ) );
        saleProduct.setTotal_amount( ticketOrder.getOrdrNum() );
        saleProduct.setBody( detail.getName() );
        BigDecimal price = detail.getPrice();
        BigDecimal num = new BigDecimal( price + "" );
        saleProduct.setMoney( num.multiply( price ).toString() );
        saleProduct.setSubject( detail.getName() );
        alipayRequest.setBizContent( JSON.toJSONString( saleProduct ) );
        //请求
        String url = "";
        try {
            url = alipayClient.pageExecute( alipayRequest ).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * 同步跳转
     * @param request
     * @throws Exception
     */

    /**
     * 支付宝服务器异步通知
     *
     * @param request
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/notifyUrl")
    public String notifyUrl(HttpServletRequest request) throws Exception {
        System.out.println( "1111" );
        // 获取支付宝GET过来反馈信息
        Map <String, String> params = new HashMap <String, String>();
        Map <String, String[]> requestParams = request.getParameterMap();
        for (Iterator <String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get( name );
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put( name, valueStr );
        }
        boolean signVerified = AlipaySignature.rsaCheckV1( params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type ); // 调用SDK验证签名
        if (signVerified) { // 验证成功 更新订单信息
            System.out.println( "异步通知成功" );
            // 商户订单号
            String out_trade_no = request.getParameter( "out_trade_no" );

            System.out.println( out_trade_no );
            String trade_status = request.getParameter( "trade_status" );
            ticketOrderService.updateOrderState( out_trade_no );
            // 修改数据库
        } else {
            System.out.println( "异步通知失败" );
        }
        return "SUCCESS";
    }


}
